package FenxiaoService

import (
	"context"
	"gdshop-font-api-go/app/entity"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"gdshop-font-api-go/library/tools/mylog"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"time"
)

// AddFenxiaoOrder 下单完成后加入分销订单
func AddFenxiaoOrder(tx *gdb.TX, oneMemberId int, orderSubData entity.OrderSub) {
	if !ConfigLevelConfig() {
		// 未开启分销功能，返回
		return
	}
	config, err := GetConfig()
	if err != nil {
		mylog.ErrorLog("ConfigLevelConfig " + err.Error())
		return
	}
	// 是否自购开启
	selfPurchaseRebate := false
	// 自购
	if config.SelfPurchaseRebate == 1 {
		selfPurchaseRebate = true
	}
	ctx := context.Background()
	// 根据  fenxiao_member_user_map 判断当前会员是普通会员还是分销商
	fuId, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_member_user_map").Where(
		"member_id", oneMemberId).Fields("fenxiao_user_id").Value()
	if err != nil {
		return
	}
	if !fuId.IsEmpty() {
		// 是普通会员，赋值
		value, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_user").Where("id", fuId.Int()).
			Fields("member_id").Value()
		if err != nil {
			mylog.ErrorLog("AddFenxiaoOrder fenxiao_user 查询错误01 " + err.Error())
			return
		}
		if value.IsEmpty() {
			mylog.ErrorLog("AddFenxiaoOrder fenxiao_user 查询错误02 找不到数据")
			return
		}
		oneMemberId = value.Int()
		selfPurchaseRebate = false
	}

	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, oneMemberId)
	if err != nil {
		if gerror.Code(err) == 6000 {
			// 没有找到数据，已可能用户未加入分销
			return
		}
		mylog.ErrorLog("AddFenxiaoOrder GetFenxiaoUserModelByMemberId error " + err.Error())
		return
	}
	fuData := g.Map{
		"order_id":     orderSubData.OrderId,
		"order_sub_id": orderSubData.Id,
		/*		"one_fenxiao_user_id":   fuModel.Id,
				"two_fenxiao_user_id":   fuModel.ParentId,
				"three_fenxiao_user_id": fuModel.ParentParentId,*/
		"create_at": time.Now().Unix(),
	}
	if selfPurchaseRebate {
		// 自购
		fuData["one_fenxiao_user_id"] = fuModel.Id
		fuData["two_fenxiao_user_id"] = fuModel.ParentId
	} else {
		// 自购关闭
		fuData["two_fenxiao_user_id"] = fuModel.ParentId
		fuData["three_fenxiao_user_id"] = fuModel.ParentParentId
	}
	// 写入分销日志中间表，做二次写入
	_, err = tx.Model("fenxiao_order").Unscoped().InsertAndGetId(fuData)
	if err != nil {
		mylog.ErrorLog("AddFenxiaoOrder InsertAndGetId error " + err.Error())
		return
	}
}
